package com.lzc.product.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lzc.product.model.Order;
import com.lzc.product.model.Product;
import com.lzc.product.model.ShoppingCar;
import com.lzc.product.service.ProductService;
import com.lzc.product.service.ProductService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet("/submitOrder.do")
public class OrderServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        Object phone = req.getSession().getAttribute("phone");
        if (phone == null) {
            //返回到登录页面
            req.getRequestDispatcher("login.jsp").forward(req, resp);
        } else {
            //反之进行生成订单，返回首页
            //获取Object映射对象(需要引入五个架包)
            ObjectMapper mapper = new ObjectMapper();
            // 将请求体中的JSON字符串转换为Map对象
            Order order = mapper.readValue(req.getReader(), Order.class);
            String phoneStr = phone.toString();
            String price = order.getTotal_price();
            List<ShoppingCar> list = order.getShopping_cars();
            ProductService service = new ProductService();
            boolean result = service.addOrder(phoneStr, price, list);
            System.out.println("添加订单结果:" + result);
            req.getRequestDispatcher("index.jsp").forward(req, resp);
        }
    }
}